package ru.spb.osll.myfit.server.handler;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;
import java.util.Vector;

import org.apache.log4j.Logger;

import ru.spb.osll.myfit.common.Page;
import ru.spb.osll.myfit.common.Table;
import ru.spb.osll.myfit.common.TableStyle;
import ru.spb.osll.myfit.server.ImportsPrinter;
import ru.spb.osll.myfit.server.parser.TableCreater;
import ru.spb.osll.myfit.server.parser.PageParserUtils;
import ru.spb.osll.myfit.server.parser.RecursiveIncludeException;

/**
 * @author kdv
 * 
 */
public class ContentHandler implements Handler {
  private Logger log = Logger.getLogger(getClass());
  protected TableCreater m_parser = new TableCreater();
  private PageLoader m_pageLoader;
  private ImportsPrinter m_importsPrinter;

  public ContentHandler(ImportsPrinter importsPrinter, String root,
                        PageLoader pageLoader) {
    m_importsPrinter = importsPrinter;
    m_pageLoader = pageLoader;
  }

  @Override
  public Table getTable(Vector<String> rawTable, TableStyle style) {
    Table table = m_parser.parseTable(rawTable);
    log.debug("Style " + style);
    table.setStyle(style);
    return table;
  }

  void savePage(Page page, PrintStream ostream) throws IOException {
    m_importsPrinter.printImports(page, ostream);
    ostream.append(PageParserUtils.pageToString(page));
  }

  @Override
  public Page loadPage(String fileName, String pagePath, String includePath)
      throws IOException {
    return m_pageLoader.loadPage(fileName, pagePath, includePath);
  }

  public Page createInlcudePage(String includePath, List<String> allPath)
      throws RecursiveIncludeException, FileNotFoundException {
    return m_pageLoader.createInlcudePage(includePath, allPath);
  }

  public Page createPageWithError(String errorMessage) {
    return m_pageLoader.createPageWithError(errorMessage);
  }

  @Override
  public void savePage(String path, Page page) throws IOException {
    log.info("Saving page, path: " + path);
    File file = new File(path);
    if (!file.exists()) {
      File dir = new File(file.getParent());
      dir.mkdirs();
      file.createNewFile();
    }

    FileOutputStream stream = null;
    try {
      stream = new FileOutputStream(file);
      savePage(page, new PrintStream(stream));
    } finally {
      if (stream != null) {
        stream.close();
      }
    }
  }
}
